﻿using System;
using System.Threading;

namespace AutoResetEventDemo
{
    class Program
    {
        //若要将初始状态设置为终止，则为 true；若要将初始状态设置为非终止，则为 false
        static AutoResetEvent oddResetEvent = new AutoResetEvent(false);
        static AutoResetEvent evenResetEvent = new AutoResetEvent(false);
        static int i = 0;
        static void Main(string[] args)
        {
            Thread thread1 = new Thread(new ThreadStart(show));
            thread1.Name = "偶数线程";
            Thread thread2 = new Thread(new ThreadStart(show));
            thread2.Name = "奇数线程";
            thread1.Start();
            Thread.Sleep(200);
            thread2.Start();

            Console.ReadKey();
        }
        public static void show()
        {
            if (i == 1) evenResetEvent.WaitOne();
            while (i <= 100)
            {
                int num = i % 2;
                if (num == 0)
                {
                    Console.WriteLine("{0}:{1}  {2}    ", Thread.CurrentThread.Name, i++, num);
                    evenResetEvent.Set();
                    oddResetEvent.WaitOne();
                }
                else
                {
                    Console.WriteLine("{0}:{1}  {2}    ", Thread.CurrentThread.Name, i++, num);
                    //如果此时AutoResetEvent 为非终止状态，则线程会被阻止，并等待当前控制资源的线程通过调用 Set 来通知资源可用。否则不会被阻止
                    oddResetEvent.Set();
                    evenResetEvent.WaitOne();
                }
            }
        }
    }
}
